// pages/map/getOrderNotGoing/getOrderNotGoing.js
const handler = require("../../../utils/function.js");
var img = handler.userImg;
var api = require("../../../api.js"),
  QQMapWX = require("../../../utils/qqmap-wx.js"),
  app = getApp();
var demo = new QQMapWX({
  key: 'EKJBZ-72L3P-FHXDL-VSLEP-JEAGJ-JTFSD' // 必填
});
Page({
  /**
   * 页面的初始数据
   */
  data: {
    dist: 0,
    message: '请稍后，代驾司机正在路上',
    img: handler.userImg,
    polyline: [{
      points: [{
        longitude: 108.93,
        latitude: 32.28
      }, {
        longitude: 108.94,
        latitude: 32.27
      }],
      color: "#0299de",
      width: 9,
      dottedLine: false,
      arrowLine: true,
    }],
    controls: [{
      id: 1,
      iconPath: '../../../images/user/icon-22.png',
      position: {
        left: 10,
        top: 10,
        width: 50,
        height: 50
      },
      clickable: true
    }, {
      id: 2,
      iconPath: '../../../images/user/icon-30.png',
      position: {
        top: 240,
        left: 10,
        width: 50,
        height: 50
      },
      clickable: true
    }, ], //人物图片定位
    driver: wx.getStorageSync("serverDriver"),
    not_going_m: 0,
    not_going_s: 0,
    startAddress: null,
    myShow: true, //显示my的页面
    alert:'司机正在赶来中,请稍后...',
    zuoyou: "icon-zuoyou", //my
    avatar: "../../../images/user/icon-07.png",
    buttonText: "登录",
    username: "未登录",
    orderGoing: false,
    homeHandlerShow: true,
    phone: "",
    order_no: '',
    is_service: 0,
    marks: [],
    make: [{ //用户位置:latitude+0.002
        iconPath: "../../../images/user/my-location.png",
        id: 0,
        latitude: 34.29418,
        longitude: 108.94712,
        width: 89,
        height: 25
      },
      { //司机位置
        iconPath: "../../../images/user/driver-img.png",
        id: 2,
        latitude: 34.30518,
        longitude: 108.94712,
        width: 20,
        height: 20
      },
      {
        iconPath: "../../../images/user/icon-07.png",
        id: 3,
        latitude: 23.099994,
        longitude: 113.324520,
        width: 50,
        height: 50
      },
    ],
    time: '',
    ordernum: 0,
    graded: 0,
    avatar_url: '',
    been_driving: 0,
    work_number:'',
    work_phone: 0,
    left_width: 750,
    distance: '',
    is_showInfo: true,
    is_pay: false, //支付成功提示
    is_pay_info: ''
  },

  backToHome(){
    wx.navigateTo({
      url:'/pages/map/driverServer/driverServer'
    })
  },

  // 地图图片点击事件
  controltap(e) {

    if (e.controlId === 1) {
      wx.navigateTo({
        url: '/pages/map/my/my',
      })
    } else {
      const addresses = handler.getLatLntHandler((res) => {
        this.setData({
          startAddress: res.startAddress, //开始位置
        })
      });
    }
  },
  // openMyPageHandler 打开我的页面
  openMyPageHandler: function() {
    const {
      pageRight,
      myShow
    } = this.data;
    console.log("openMyPageHandler", pageRight, myShow);
    if (myShow) {
      this.setData({
        pageRight: 620,
        left_width: 130,
        myShow: !myShow,
        controls: [{
          id: 1,
          iconPath: '../../../images/user/icon-33.png',
          position: {
            top: 144,
            left: 10,
            width: 41,
            height: 41
          },
          clickable: true
        }]
      });
    } else {
      this.setData({
        pageRight: 0,
        left_width: 750,
        myShow: !myShow,
        controls: [{
          id: 1,
          iconPath: '../../../images/user/icon-22.png',
          position: {
            left: 10,
            top: 10,
            width: 50,
            height: 50
          },
          clickable: true
        }, {
          id: 2,
          iconPath: '../../../images/user/icon-30.png',
          position: {
            top: 240,
            left: 10,
            width: 50,
            height: 50
          },
          clickable: true
        }, ],
      });
      this.changeIcon()
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({
      order_no: options.order_no
    })
    // 获取优惠券
    if (options.uid) {
      app.shareCouponsMessage(options.uid)
    }
    if (options.showdistance) {
      this.setData({
        is_distance: false,
        message: '代驾司机已到达'
      })
    }
    // 确认预约订单提前出发

  },
  // 确认预约订单提前出发
  going_order: function() {
    let that = this;
    wx.showModal({
      title: '提示',
      content: '预约时间未到，确认要提前出发吗？',
      success: function(e) {
        var setout = e.confirm ? 2 : 3;
        app.request({
          url: api.order_branch.confirm,
          method: 'post',
          data: {
            order_no: that.data.order_no,
            setout: setout
          },
          success: function(rs) {}
        })
      }
    })
  },
  // callPhoneHandler  打电话功能
  callDriverPhoneHandler: function() {
    handler.callPhoneHandler(this.data.work_phone)
  },
  // callServerPhoneHandler 打客服电话号码
  callServerPhoneHandler: function(e) {
    console.log(e.currentTarget.dataset.phone)
    handler.callPhoneHandler(e.currentTarget.dataset.phone)
  },
  apply_refund:function(){
    console.log('申请退单')
    var that =this;
    app.request({
      url: api.order.apply_refund,
      method: 'post',
      data: {
        order_no: that.data.order_no,
      },
      success: function (rs) {
        console.log('申请退款结果',rs);
        if (rs.code == 1) {
          wx.showToast({
            title: '订单取消已成功',
          })
          clearInterval(this.timeTask)
          setTimeout(function(){
            wx.reLaunch({
              url: '../driverServer/driverServer',
            })
          },3000)
        } else {
          wx.showToast({
            title: rs.msg,
          })
        }
      }
    })
  },
  // deleteOrderHandler 删除订单功能 cancel_order
  deleteOrderHandler: function(e) {
    var that = this;
    let formid = e.detail.formId
    app.request({
      url: api.order_branch.violations,
      method: 'post',
      data: {
        formid: formid,
        order_no: that.data.order_no
      },
      success: function(rs) {
        //code 0 获取信息失败 1支付金额 2 可以取消订单
        if (rs.code == 1) {
          wx.showModal({
            title: '提示',
            content: '下单超过' + rs.data.time_limit + '分钟,需交付违约金' + rs.data.violations + '元',
            success: function(res) {
              if (res.confirm) {
                // 调支付接口
                that.pay_penalty({
                  formid: formid,
                  price: rs.data.violations
                })
              }
            }
          })
        } else if (rs.code == 2) {
          that.deleteOrder(formid)
        } else {
          wx.showModal({
            title: '提示',
            content: rs.msg,
          })
        }
      }
    })
  },
  // deleteOrder 取消订单事件
  deleteOrder: function(e) {
    var that = this;
    wx.showModal({
      title: '提示',
      content: '确认要取消订单',
      success: function(res) {
        if (res.confirm) {
          app.request({
            url: api.order.cancel_order,
            method: 'post',
            data: {
              formid: e,
              order_no: that.data.order_no,
            },
            success: function(rs) {
              if (rs.code == 1) {
                wx.showToast({
                  title: '订单取消已成功',
                })
                clearInterval(this.timeTask)
                wx.reLaunch({
                  url: '../driverServer/driverServer',
                })
                // handler.intoPageHandler('');
              } else {
                wx.showToast({
                  title: rs.msg,
                })
              }
            }
          })
        }
      }
    })

  },
  // 支付违约金
  pay_penalty: function(data) {
    let order_no = this.data.order_no;
    let formid = data.formid;
    let price = data.price;
    let that = this;
    app.request({
      url: api.order_branch.gold,
      method: 'post',
      data: {
        formid: formid,
        order_no: order_no
      },
      success: function(rs) {
        console.log(rs, '违约金')
        wx.requestPayment({
          timeStamp: rs.data.timeStamp,
          nonceStr: rs.data.nonceStr,
          package: rs.data.package,
          signType: rs.data.signType,
          paySign: rs.data.paySign,
          success: function(res) {
            that.setData({
              is_pay: true,
              is_pay_info: "支付成功",
            })
            clearInterval(that.timeTask)
            wx.navigateBack({
              delta: 1
            })
          },
          fail: function() {
            that.setData({
              is_pay: true,
              is_pay_info: "支付失败",
            })
            setTimeout(() => {
              that.setData({
                is_pay: false,
                is_pay_info: "支付失败",
              })
            }, 1500)
          }
        })
      }
    })
  },
  // timeTask 时间业务
  timeTask: function() {
    var not_going_s = this.data.not_going_s;
    var not_going_m = this.data.not_going_m;
    not_going_s++;
    if (not_going_s > 59) {
      not_going_s = 0;
      not_going_m++;
    }
    this.setData({
      not_going_s,
      not_going_m
    });
  },
  // orderGoingHandler 订单进行中事件
  orderGoingHandler: function() {
    wx.showToast({
      title: '目前还没有正在进行中的订单',
      icon: "none"
    })
    this.setData({
      orderGoing: false
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {},
  /**
   * 生命周期函数--监听页面显示
   */
  get_line_and_count_distance() {
    let that = this;
    let start = this.data.startAddress;
    let end = this.data.endAddress;
    if (start && end) {
      // 获取位置路线
      this.getPolyline(start, end)
      // 计算距离
      // this.get_distance(start, end, res => {
      //   let km_num = (res.distance.elements[0].distance / 1000).toFixed(1)
      // 获取预计金额
      // app.request({
      //   url: api.order_forecast.order_forecast,
      //   method: "post",
      //   data: {
      //     mileage: km_num
      //   },
      //   success(data) {
      //     console.log("order_forecast")
      //     console.log(data)
      //     that.setData({
      //       price: data.data.price
      //     })
      //   }
      // })
      // this.setData({ distance: km_num, is_distance: true });
      // })
    }
  },
  // 获取位置路线

  // 绘制图标
  mark_icon() {
    let that = this
    let start = this.data.startAddress;
    let end = this.data.endAddress;
    //添加图标
    let make = [];
    if (start) {
      make[0] = {
        id: 0,
        iconPath: "/images/user/icon-44.png",
        latitude: start.location.lat,
        longitude: start.location.lng,
        width: 40,
        height: 40
      };

    }
    if (end) {
      make[1] = {
        id: 1,
        iconPath: "/images/user/icon-43.png",
        latitude: end.location.lat,
        longitude: end.location.lng,
        width: 40,
        height: 40
      };

    }

    that.setData({
      make: make
    });
  },
  onShow: function() {
    this.getDriverInfo();
    this.getorderstatus();
    if (wx.getStorageSync("userMessage") !== "") {
      this.setData({
        avatar: wx.getStorageSync("userMessage").avatar,
        username: wx.getStorageSync("userMessage").username,
        buttonText: wx.getStorageSync("userMessage").buttonText,
        phone: wx.getStorageSync("phonep"),
      });
    }
    var that = this;
    // var time = setInterval(() => {
    if (that.data.is_service == 2) {
      clearInterval(time);
      wx.removeStorageSync("is_delete");
      wx.redirectTo({
        url: '../orderGoing/orderGoing?order_no=' + that.data.order_no,
      })
    } else if (that.data.is_service == 1) {
      wx.removeStorageSync("is_delete");
      clearInterval(time);
      wx.redirectTo({
        url: '../orderGoing/orderGoing?order_no=' + that.data.order_no,
      })
    } else {
      that.postionTask();
    }
    // }, 5000);
    // //时间定时器修改
    // this.setData({time})
    handler.getLatLntHandler(res => {
      that.setData({
        startAddress: res.startAddress, //开始位置
      })
    })
    // 按钮重定位
    this.changeIcon()
    this.update_delete()
  },
  getorderstatus(){
    var that =this;
    app.request({
      url: api.order.orderstatus,
      method: 'post',
      data: {
        order_no: that.data.order_no,
        is_service:1,
      },
      success: function (rs) {
        console.log(rs)
        if (rs) {
         wx.showToast({
           title: '司机已到达',
           icon:'none'
         })
         that.setData({
          alert:'司机已到达您的位置'
        })
          clearTimeout()
          that.going_order()
        }else{
         setTimeout(function(){
            that.getorderstatus()
         }, 10000);
        } 
      }
    })
  },
  going_order(){

    var that =this;
    app.request({
      url: api.order.orderstatus,
      method: 'post',
      data: {
        order_no: that.data.order_no,
        is_service:0
      },
      success: function (rs) {
        console.log(rs)
        if (rs) {
         wx.showToast({
           title: '开始行程',
           icon:'none'
         })
          clearTimeout()
          setTimeout(function(){
            wx.navigateTo({
             url: '/pages/map/orderGoing/orderGoing?order_no='+that.data.order_no,
           })
         },3000)
        }else{
         setTimeout(function(){
            that.going_order()
         }, 10000);
        } 
      }
    })  
  },
  getDriverInfo() {
    var that = this;
    setTimeout(() => {
      let order_no = that.data.order_no,
        info = wx.getStorageSync('driver_now_position'),
        end = wx.getStorageSync('startAddress');
      console.log("监听司机位置", end)
      if (info) {
        if (info['order_no'] == order_no) {
          that.getPolyline(JSON.parse(info['data'].start_position_point), end['location']);
          that.setData({
            dist: info['data'].dist,
            marks: [{ //司机位置
              iconPath: "../../../images/user/icon-50.png",
              id: 1,
              callout: {
                content: '司机当前位置',
              },
              latitude: JSON.parse(info['data'].start_position_point).latitude,
              longitude: JSON.parse(info['data'].start_position_point).longitude,
              width: 40,
              height: 40
            }, { //起点位置
              iconPath: "../../../images/driver/icon-44.png",
              id: 2,
              latitude: end['location'].lat,
              longitude: end['location'].lng,
              width: 40,
              height: 40
            }]
          })
          if (info['data'].is_service == 4) {
            this.setData({
              message: '代驾司机已到达'
            })
          } else {
            that.getDriverInfo();
          }
          // 显示司机坐标

        } else {
          that.getDriverInfo();
        }
      } else {
        that.getDriverInfo();
      }
    }, 5000)
  },
  getPolyline: function(start, end) {
    const that = this;
    const {
      polyline
    } = this.data;
    const froms = start.latitude + "," + start.longitude + "&to=" + end.lat + "," + end.lng;
    wx.request({
      url: `https://apis.map.qq.com/ws/direction/v1/driving/?from=${froms}&key=EKJBZ-72L3P-FHXDL-VSLEP-JEAGJ-JTFSD`,
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function(res) {
        console.log(res);
        if (res.data.status === 384) {} else {
          var coors = res.data.result.routes[0].polyline;
          for (var i = 2; i < coors.length; i++) {
            coors[i] = coors[i - 2] + coors[i] / 1000000
          }
          const points = [];
          for (var j = 0; j < coors.length; j += 2) {
            points[points.length] = {
              longitude: coors[j + 1],
              latitude: coors[j]
            }
          }
          polyline[0].points = points;
          that.setData({
            polyline: polyline
          })
        }
      },
      fail: function() {
        // showToast('网络出现错误', "none")
      }
    })
  },
  // 30s
  update_delete() {
    // 30s 隐藏删除按钮
    let is_delete = wx.getStorageSync("is_delete") || false
    if (!is_delete) {
      this.setData({
        is_delete: true
      })
      setTimeout(() => {
        wx.setStorageSync("is_delete", true)
        this.setData({
          is_delete: false
        })
      }, 30000)
    } else {
      this.setData({
        is_delete: false
      })
    }
  },
  // 获取距离
  get_distance: function(start, target, callback) {
    demo.calculateDistance({
      from: {
        latitude: start.location.lat,
        longitude: start.location.lng
      },
      to: [{
        latitude: target.location.lat,
        longitude: target.location.lng
      }],
      success: function(res) {
        console.log(res.result.elements[0].distance);
        callback({
          distance: res.result
        })
      },
      fail: function(res) {
        callback(res)
      },
      complete: function(res) {
        console.log(res);
      }
    });
  },

  /*
   * 定时获取订单状态及代驾人员位置
   */
  postionTask: function() {
    var that = this;
    app.request({
      url: api.order.waiting,
      method: 'post',
      data: {
        order_no: that.data.order_no,
      },
      success: function(rs) {
        if (rs.code == 1) {
          wx.setStorageSync("startAddress", rs.data.startAddress);
          wx.setStorageSync("endAddress", rs.data.endAddress);
          that.setData({
            order_no: rs.data.order_no,
            startAddress: rs.data.lang,
            endAddress: {
              location: rs.data.target_adds_location
            },
            make: rs.data.start_location,
            is_service: rs.data.is_service,
            drivername: rs.data.userinfo.real_name,
            ordernum: rs.data.userinfo.ordernum,
            graded: rs.data.userinfo.graded,
            avatar_url: rs.data.userinfo.avatar_url,
            been_driving: rs.data.userinfo.been_driving,
            work_number:rs.data.userinfo.work_number,
            work_phone: rs.data.userinfo.work_phone,
            signature: rs.data.userinfo.signature,
            distance: rs.data.apart,
            serverphone: rs.data.serverphone,
            price: rs.data.total_price,
            is_distance: true
          })
          if (rs.data.is_out == 1 && that.data.is_showInfo) {
            that.setData({
              is_showInfo: false
            })
            // that.going_order()
          }
        }
        //绘制路线以及添加图片
        that.mark_icon()
        // that.get_line_and_count_distance()
      }
    })
  },
  // 用户信息事件
  /**loginHandler用户登录页面 */
  loginHandler: function(e) {
    if (this.data.buttonText === "登录") {
      handler.loginHandler((res) => {
        // console.log("用户信息事件",res);
        this.setData({
          res,
        });
        const that = this;
        wx.showModal({
          title: '获取手机号码',
          content: '我们需要获取你的电话号码，一边与和你保持实时的联系，防止你的订单丢失',
          success: function(res) {
            if (res.confirm) {
              wx.reLaunch({
                url: '../../user/getPhone/getPhone'
              })
              //   wx.wx.reLaunch({url:})
              //     handler.intoPageHandler("../../user/getPhone/getPhone");
            }
          },
          fail: function() {
            wx.showToast({
              title: '登录失败',
              icon: "none"
            })
          }
        })
      })
    } else {
      this.setData({
        avatar: "../../../images/user/icon-07.png",
        username: "未登录",
        buttonText: "登录",
        phone: ""
      });
    }
  },
  // intoPageHandler 页面跳转
  intoPageHandler: function(e) {
    handler.intoPageHandler(e.currentTarget.dataset.skip)
  },
  // 修改用户和一键定位位置
  changeIcon: function() {
    const that = this;
    const {
      controls
    } = this.data;
    wx.getSystemInfo({
      success: function success(res) {
        var controlsH = res.windowWidth / 750 * 700; //计算一像素的宽度 res.windowWidth/750
        var map_height = res.windowHeight - controlsH;
		var map_width = res.windowWidth
        // console.log(res, '2222222222')
        controls[1] = {
          id: 2,
          iconPath: '../../../images/user/icon-30.png',
          position: {
            top: map_height - 56,
            left: map_width - 50,
            width: 40,
            height: 40
          },
          clickable: true
        };
        that.setData({
          winPath: {
            w: res.windowWidth,
            h: res.windowHeight
          },
          map_height,
          controls,
        });
      }
    });
  },
  //清除时间定时器
  onUnload() {
    var time = this.data.time;
    clearInterval(time)
  },
  onHide() {
    var time = this.data.time;
    clearInterval(time)
  },
  // 用户分享
  onShareAppMessage: function() {
    let title = app.shareAppMessage().title;
    let imageUrl = app.shareAppMessage().imageUrl;
    let desc = app.shareAppMessage().desc;
    let path = app.shareAppMessage().path;
    // console.log(app.shareAppMessage())
    return {
      title: title,
      imageUrl: imageUrl,
      desc: desc,
      path: path,
    }
  },
})